﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.DataAccess.Model.Projects;
using Core.Framework.EntityExtend;
using Core.Framework.Model.Common;
using Core.IBusiness.IProjectModule;
using Core.IBusiness.IProjectModule.Model;

namespace Core.Business.ProjectModule
{
    [NotUseBaseHttpPipelineInfo]
    public class ProjectUserApiService : IProjectUserApiService
    {
        public MethodResult<ProjectUserApiOrder> GetOrder(int key)
        {
            try
            {
                using (var context = new ProjectContext())
                {
                    var orderInfo = context.ProjectUserApiOrder.Where(a => a.Id == key).FirstOrDefault();

                    if (null == orderInfo)
                    {
                        return new MethodResult<ProjectUserApiOrder> { IsFinished = false, Discription = "订单不存在" };
                    }

                    return new MethodResult<ProjectUserApiOrder> { Date = orderInfo, IsFinished = true };

                }
            }
            catch (Exception e)
            {
                return new MethodResult<ProjectUserApiOrder> { IsFinished = false, Discription = e.Message };
            }
        }

        public MethodResult<decimal> GetOrderPrice(int key)
        {
            try
            {
                using (var context = new ProjectContext())
                {
                    var orderInfo = context.ProjectUserApiOrder.Where(a => a.Id == key).FirstOrDefault();

                    if (null == orderInfo)
                    {
                        return  new MethodResult<decimal>{ IsFinished = false, Discription = "查询支付订单不存在"};
                    }

                    if (orderInfo.Pay)
                    {
                        return  new MethodResult<decimal>{ IsFinished = false, Discription = "查询支付订单已支付"};
                    }

                    return new MethodResult<decimal>{ Date = orderInfo.ApiMoney ?? 0, IsFinished = true};

                }
            }
            catch (Exception e)
            {
                return  new MethodResult<decimal>{ IsFinished = false, Discription = e.Message};
            }
        }

        public MethodResult<List<ProjectUserApiOrder>> GetUserOrders(int userKey, Pagination pagination)
        {
            try
            {
                using (var context = new ProjectContext())
                {
                    var orderInfo = context.ProjectUserApiOrder.Where(a => a.UserId == userKey).Pagination(pagination);
                    return new MethodResult<List<ProjectUserApiOrder>> { Date = orderInfo, IsFinished = true };

                }
            }
            catch (Exception e)
            {
                return  new MethodResult<List<ProjectUserApiOrder>> { IsFinished = false, Discription = e.Message};
            }
        }

        public MethodResult UseApiCount(int projectKey, int apiKey)
        {
            try
            {
                using (var context = new ProjectContext())
                {
                    context
                        .ProjectUserApi
                        .BulkUpdate("apiCount -= 1", "apiFreezeCount += 1")
                        .Where(a => a.ProjectId == projectKey && a.ApiKey == apiKey);

                    context.BeginSaveChanges(out string msg);

                    if (string.IsNullOrWhiteSpace(msg))
                    {
                        return new MethodResult { IsFinished = true };
                    }
                    else
                    {
                        return new MethodResult { IsFinished = false, Discription = msg};
                    }

                }
            }
            catch (Exception e)
            {
                return new MethodResult { IsFinished = false, Discription = e.Message };
            }
        }


        public MethodResult<KeyValuePair<bool,int>> IsApiAvailability(int projectKey, int apiKey)
        {
            try
            {
                using (var context = new ProjectContext())
                {
                    // 查询服务信息
                    var apiInfo = context.ProjectUserApi.Where(a => a.ProjectId == projectKey && a.ApiKey == apiKey).FirstOrDefault();

                    var result = new MethodResult<KeyValuePair<bool, int>> { IsFinished = true, Date = new KeyValuePair<bool, int>(false, 0) };

                    // 检查服务是否存在
                    if (null == apiInfo)
                    {
                        result.IsFinished = false;
                        result.Discription = "产品尚未订阅该服务";
                        return result;
                    }

                    // 检查是否存在结余数量
                    if (apiInfo.ApiCount > 0)
                    {
                        result.Date = new KeyValuePair<bool,int>(true, apiInfo.ApiCount ?? 0);
                    }
                    // 检查结束时间是否符合
                    else if (apiInfo.EndTime > DateTime.Now)
                    {
                        var days = (apiInfo.EndTime - DateTime.Now).Value.TotalDays;
                        int.TryParse(Math.Round(days).ToString(),out int day);
                        result.Date = new KeyValuePair<bool, int>(true, day);
                    }
                    else
                    {
                        result.Discription = "服务已过期";
                    }

                    return result;

                }
            }
            catch (Exception e)
            {
                return new MethodResult<KeyValuePair<bool, int>> { Discription = e.Message, IsFinished = false };
            }

        }

        public MethodResult<int> UserAddOrder(ProjectUserApiOrder model)
        {
            try
            {
                using (var context = new ProjectContext())
                {
                    context.ProjectUserApiOrder.Add(model);
                    var row = context.SaveChanges();
                    return new MethodResult<int> { Date = row, IsFinished = true};
                }
            }
            catch (Exception e)
            {
                return new MethodResult<int> { Discription = e.Message, IsFinished = false};
            }
        }

        public MethodResult<int> UserOrderPay(int key)
        {
            try
            {
                using (var context = new ProjectContext())
                {
                    // 查询付款订单
                    var orderInfo = context.ProjectUserApiOrder.Where(a => a.Id == key).FirstOrDefault();

                    // 判断是否存在
                    if (null == orderInfo)
                    {
                        return new MethodResult<int> { IsFinished = false, Discription = "订单不存在" };
                    }

                    // 更新状态为已付款
                    orderInfo.Pay = true;

                    // 构造用户使用API
                    // ApiCount 比 ApiDay 权重高
                    var userApi = new ProjectUserApi
                    {
                        ApiCount = orderInfo.ApiCount,
                        ProjectId = orderInfo.ProjectId,
                        ApiFreezeCount = 0,
                        ApiKey = orderInfo.ApiKey,
                        UserId = orderInfo.UserId,
                        EndTime = DateTime.Now.AddDays(orderInfo.ApiDay ?? -1),
                        AddTime = DateTime.Now
                    };

                    // 写入用户服务信息
                    context.ProjectUserApi.Add(userApi);

                    // 提交保存
                    var row = context.SaveChanges();

                    return new MethodResult<int> { Date = row, IsFinished = true };
                }
            }
            catch (Exception e)
            {
                return new MethodResult<int> { Discription = e.Message, IsFinished = false };
            }
        }

        public MethodResult<List<ProjectApiInfo>> GetProjectApiList(int projectKey)
        {
            try
            {
                using (var context = new ProjectContext())
                {

                    int?[] apiKeys = new int?[] {
                        (int)APIServiceEnum.BBS,
                        (int)APIServiceEnum.Queue,
                        (int)APIServiceEnum.Shop };

                    // 查询服务信息
                    var apiServices = context.ProjectUserApi
                        .Where(a => a.ProjectId == projectKey && apiKeys.Contains(a.ApiKey))
                        .Select(a => new { a.ApiCount, a.EndTime, a.ApiKey })
                        .ToList();

                    var result = new MethodResult<List<ProjectApiInfo>>
                    {
                        IsFinished = true,
                        Date = new List<ProjectApiInfo>()
                    };

                    // 检查服务是否存在
                    if (null != apiServices && apiServices.Count > 0)
                    {
                        foreach (var apiInfo in apiServices)
                        {
                            var model = new ProjectApiInfo();

                            // 检查是否存在结余数量
                            if (apiInfo.ApiCount > 0)
                            {
                                model.IsApiSubscribe = true;
                                model.IsApiAvailability = true;
                            }
                            // 检查结束时间是否符合
                            else if (apiInfo.EndTime > DateTime.Now)
                            {
                                model.IsApiSubscribe = true;
                                model.IsApiAvailability = true;
                            }
                            else
                            {
                                model.IsApiSubscribe = true;
                                model.IsApiAvailability = false;
                            }

                            switch (apiInfo.ApiKey)
                            {
                                case (int)APIServiceEnum.BBS:
                                    model.Code = "BBS";
                                    model.Title = "信息流";
                                    break;
                                case (int)APIServiceEnum.Queue:
                                    model.Code = "Queue";
                                    model.Title = "消息队列";
                                    break;
                                case (int)APIServiceEnum.Shop:
                                    model.Code = "Shop";
                                    model.Title = "电商";
                                    break;
                            }

                            result.Date.Add(model);
                        }
                    }

                    #region Default LIST

                    if (!result.Date.Any(a => a.Code == "BBS"))
                        result.Date.Add(new ProjectApiInfo
                        {
                            Code = "BBS",
                            Title = "信息流"
                        });

                    if (!result.Date.Any(a => a.Code == "Queue"))
                        result.Date.Add(new ProjectApiInfo
                        {
                            Code = "Queue",
                            Title = "消息队列"
                        });

                    if (!result.Date.Any(a => a.Code == "Shop"))
                        result.Date.Add(new ProjectApiInfo
                        {
                            Code = "Shop",
                            Title = "电商"
                        });

                    #endregion

                    return result;

                }
            }
            catch (Exception e)
            {
                return new MethodResult<List<ProjectApiInfo>> { Discription = e.Message, IsFinished = false };
            }
        }
    }
}
